package cn.tedu.v4;

import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * 多人聊天室 Version 4
 */
public class Client {

    private static final String HOST = "172.20.10.5";
    private static final int PORT = 2356;

    private Socket socket;
    private String ip;

    private PrintWriter pw;
    private BufferedReader br;

    public Client() {
        try {

            socket = new Socket(HOST, PORT);
            ip = socket.getInetAddress().getHostAddress();
            br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));
            pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8")), true);

        } catch (SocketException e) {
            System.out.println("连接被重置或断开");
        } catch (UnknownHostException e) {
            System.out.println("IP地址有问题，请询问服务器端");
        } catch (IOException e) {
            System.out.println("客户端主动退出了：断开连接");
        }
    }

    public void start() {
        try {

            new Thread(() -> {
                try {
                    String message;
                    while ((message = br.readLine()) != null) {
                        System.out.println("服务器端说：" + message);
                    }
                    System.out.print("客户端请输入");
                } catch (IOException e) {
                    System.out.println("服务器端发的消息断开了");
                }
            }).start();
            Scanner input = new Scanner(System.in);
            while (true) {
                System.out.println("客户端请输入：");
                String say = input.nextLine();
                pw.println("客户端说" + say);
                System.out.println("写出完毕");
            }
        } finally {
            try {
                if (pw != null) ;
                pw.close();
                if (br != null) ;
                br.close();
            } catch (IOException e) {
                System.out.println("服务器端通讯失败");
            }


            if (socket != null && !socket.isClosed()) {
                System.out.println("客户端关闭成功");
                try {
                    socket.close();
                } catch (IOException e) {
                    System.out.println("客户端关闭失败");
                }
            }
        }
    }

    public static void main(String[] args) {
        new Client().start();
    }
}
